<template>
	<div class="padding20" style="height: 1000px">
		<el-divider content-position="left">审批内容</el-divider>
		<iframe v-show="isIframeLoaded" ref="previewPage" class="result-wrapper" frameborder="0" :src="iframePath" @load="iframeLoad" />
		<div v-show="!isIframeLoaded" v-loading="true" class="result-wrapper"></div>
		<div>
			<el-divider content-position="left">审批进度</el-divider>
			<!-- <el-table ref="multipleTable" :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border>
				<el-table-column prop="taskName" label="审批节点" :show-overflow-tooltip="true"></el-table-column>
				<el-table-column prop="userName" label="审批人" :show-overflow-tooltip="true"></el-table-column>
				<el-table-column prop="endTime" label="审批时间" :show-overflow-tooltip="true"></el-table-column>
				<el-table-column prop="approveStatus" label="审批状态" :show-overflow-tooltip="true"></el-table-column>
				<el-table-column prop="approveOpinion" label="审批意见" :show-overflow-tooltip="true"></el-table-column>
			</el-table> -->
			<self-appoint ref="SelfAppoint" v-model="params" :actKey="$route.query.actKey" :pid="$route.query.pid" :engineVersion="$route.query.engineVersion" readonly request></self-appoint>
		</div>
	</div>
</template>

<script>
import { exportDefault } from "@/components/fortress-approve-draggable/utils/index"
import { makeUpHtml } from "@/components/fortress-approve-draggable/generator/html"
import { makeUpJs } from "@/components/fortress-approve-draggable/generator/datajs"
import { makeUpCss } from "@/components/fortress-approve-draggable/generator/css"
import { formconfigInfo } from "@/api/flowable/formconfig.js"
import { completeTask } from "@/api/approves/approves.js"
import { parse } from "@babel/parser"

const editorObj = {
	html: null,
	js: null,
	css: null,
}
export default {
	data() {
		return {
			formLabelWidth: "120px",
			visible: false,
			isIframeLoaded: false,
			isInitcode: false, // 保证open后两个异步只执行一次runcode
			isRefreshCode: false, // 每次打开都需要重新刷新代码
			htmlCode: "",
			jsCode: "",
			cssCode: "",
			params: {},
			formData: {},
			generateConf: { type: "file" },
			formConfigData: {
				id: "",
				designContent: "",
				tbContent: "",
				viewContent: "",
			},
			form: {},
			rowId: "",
			iframePath: process.env.NODE_ENV === "production" ? "/admin/preview.html?disabled=" : "/preview.html?disabled=",
			approveForm: {
				tid: "",
				id: "",
				task: "",
				approveStatus: "",
				approveOpinion: "",
			},
			approveStatusList: [
				{
					name: "同意",
					code: "1",
				},
				{
					name: "不同意",
					code: "2",
				},
			],
			approveRules: {
				approveStatus: [{ required: true, message: "请选择审核意见", trigger: "blur" }],
			},
			queryForm: {
				pid: "",
			},
			tableData: [],
		}
	},
	created() {
		let _this = this
		let tid = this.$route.query.tid || ""
		let id = this.$route.query.id || ""
		this.$nextTick(() => {
			this.$refs.SelfAppoint.getData()
		})
		this.queryForm.pid = this.$route.query.pid || ""
		this.init(tid, id)
		// this.queryList()
		window.dataeditfinish = function() {
			_this.$message({
				type: "success",
				message: "操作成功!",
			})
			_this.$emit("refreshData")
			_this.closeHandler()
		}
	},
	computed: {},
	watch: {},
	methods: {
		init(tbId, id) {
			this.approveForm.tid = tbId
			this.approveForm.id = id
			;(this.formConfigData.id = tbId + ""),
				(this.rowId = id),
				formconfigInfo(tbId).then(resp => {
					if (resp.code == 0) {
						if (resp.data.viewContent) {
							this.visible = true
							this.formData = JSON.parse(resp.data.viewContent)
							this.formData.formBtns = false
							this.formData.disabled = true
							this.onOpen()
						} else {
							this.drawingList = []
						}
					}
				})
		},
		onOpen() {
			const { type } = this.generateConf
			this.htmlCode = makeUpHtml(this.formData, type)
			this.jsCode = makeUpJs(this.formData, type, this.formConfigData.id, this.rowId)
			this.cssCode = makeUpCss(this.formData)
			this.setEditorValue("editorHtml", "html", this.htmlCode)
			this.setEditorValue("editorJs", "js", this.jsCode)
			this.setEditorValue("editorCss", "css", this.cssCode)
			this.runCode()
		},
		setEditorValue(id, type, codeStr) {
			editorObj[type] = codeStr
		},
		runCode() {
			const jsCodeStr = editorObj.js
			try {
				const ast = parse(jsCodeStr, { sourceType: "module" })
				const astBody = ast.program.body
				if (astBody.length > 1) {
					this.$confirm("js格式不能识别，仅支持修改export default的对象内容", "提示", {
						type: "warning",
					})
					return
				}
				if (astBody[0].type === "ExportDefaultDeclaration") {
					const postData = {
						type: "refreshFrame",
						data: {
							generateConf: this.generateConf,
							html: this.htmlCode,
							js: jsCodeStr.replace(exportDefault, ""),
							css: this.cssCode,
							scripts: [],
							links: [],
						},
					}
					let _this = this
					let timer = setInterval(function() {
						if (_this.$refs.previewPage) {
							_this.isIframeLoaded = true
							_this.$refs.previewPage.contentWindow.postMessage(postData, location.origin)
							clearInterval(timer)
						}
					}, 50)
				} else {
					this.$message.error("请使用export default")
				}
			} catch (err) {
				// this.$message.error(`js错误：${err}`)
				console.error(err)
			}
		},
		iframeLoad() {
			// if (!this.isInitcode) {
			//   this.isIframeLoaded = true
			//   this.isRefreshCode && (this.isInitcode = true) && this.runCode()
			// }
			this.runCode()
		},
		//关闭
		closeHandler() {
			this.rowId = ""
			this.visible = false
			this.isIframeLoaded = false
			this.isInitcode = false // 保证open后两个异步只执行一次runcode
			this.isRefreshCode = false // 每次打开都需要重新刷新代码
		},
		//提交表单数据
		submitForm() {
			this.$refs["approveForm"].validate(valid => {
				if (valid) {
					console.log(this.approveForm)
					completeTask(this.approveForm).then(resp => {
						if (resp.code == 0) {
							this.$message({
								type: "success",
								message: "操作成功!",
							})
							this.$router.go(-1)
						} else {
							this.$msg({
								message: resp.msg,
								type: "error",
							})
						}
					})
				} else {
					console.log("error submit!!")
					return false
				}
			})
		},
	},
}
</script>

<style lang="scss" scoped>
@import "@/components/fortress-approve-draggable/styles/index";
@import "@/components/fortress-approve-draggable/styles/home";

.result-wrapper {
	overflow-y: auto;
	height: 40vh;
	width: 100%;
	overflow: auto;
	padding: 12px;
	box-sizing: border-box;
}
</style>
